import { routerRedux } from 'dva/router';
import * as usersService from '../services/users';
import { message } from 'antd';

export default {
  namespace: 'users',
  state: {
  	lsit:[],
  	total:null,
  	page: null
  },
  reducers: {
  	save(state, { payload: { data: list, total, page } }) {
      /*alert("reducers");*/
      console.log(list);
      return { ...state, list, total, page };
    }
  },
  effects: {
  	*fetch({ payload: { page = 1 } }, { call, put }) {
     /* alert("effects");*/
      const { data} = yield call(usersService.fetch, { page });
      yield put({
        type: 'save',
        payload: {
          data:data.records,
          total: data.total,
          page: data.current,
        }
      });

    },
    *create({ payload: values }, { call, put }) {
      const data = yield call(usersService.create, values);
      if(data){
        yield put({ type: 'reload' });
      }
    },
    *login({ payload: values }, { call, put }) {
      const data = yield call(usersService.login, values);
      console.log("data.responseCode:"+data.data.responseCode);
      if(data.data.responseCode=='0000'){
        console.log("页面跳转");
        yield put(routerRedux.push('/main'));
      }else{
        message.error("用户名或密码错误", 2.5);
        /*yield put(routerRedux.push('/error404'));*/
      }
    },
    *patch({ payload: {id,values} }, { call, put }) {
      const data = yield call(usersService.patch, id, values);
      if(data){
        yield put({ type: 'reload' });
      }
    },
     *remove({ payload: id}, { call, put }) {
      const data = yield call(usersService.remove, id);
      if(data){
        yield put({ type: 'reload' });
      }
    },
    *reload(action, { put, select }) {
      const page = yield select(state => state.users.page);
      yield put({ type: 'fetch', payload: { page } });
    }
  },
  subscriptions: {
  	setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
       /* alert("subscriptions");*/
        if (pathname === '/users') {
          dispatch({ type: 'fetch', payload: query });
        }
      });
    }
  }
};
